import { Component } from 'react'
import Moment from 'react-moment'
import { Button, Form, Select } from 'antd'
import { FormComponentProps } from 'antd/lib/form'
import { capitalize } from 'lodash'
import { Order } from '../type'
import Items from './items'

interface Props {
  data: Order
  editing: boolean
  onSubmit: (x: Partial<Order>) => void
  onEdit: () => void
  onCancel: () => void
}

@(Form.create as any)()
class OrderForm extends Component<Props & FormComponentProps> {
  layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 8 },
  }

  handleSubmit = (event: React.FormEvent<never>) => {
    event.preventDefault()
    const {
      data: { id },
      onSubmit,
      form,
    } = this.props
    form.validateFieldsAndScroll(
      (error: Error, values: Record<keyof Order, string>) =>
        !error &&
        onSubmit({
          id,
          state: values.state,
        }),
    )
  }

  render() {
    return (({ data, editing, onEdit, onCancel, form }) => (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item {...this.layout} label="Create Time">
          <Moment calendar>{data.createdAt}</Moment>
        </Form.Item>
        <Form.Item {...this.layout} label="Update Time">
          <Moment calendar>{data.updatedAt}</Moment>
        </Form.Item>
        <Form.Item {...this.layout} label="Customer">
          {data.customer && data.customer.name}
        </Form.Item>
        <Form.Item {...this.layout} label="Items">
          <Items data={data.items} />
        </Form.Item>
        <Form.Item {...this.layout} label="State">
          {form.getFieldDecorator('state', {
            initialValue: data.state,
            rules: [
              {
                required: true,
                message: 'Please input the state',
              },
            ],
          })(
            <Select disabled={!editing}>
              {STATES.map(x => (
                <Select.Option key={x} value={x}>
                  {capitalize(x)}
                </Select.Option>
              ))}
            </Select>,
          )}
        </Form.Item>
        <Form.Item wrapperCol={{ offset: this.layout.labelCol.span }}>
          {!editing ? (
            <Button onClick={onEdit}>Edit</Button>
          ) : !data.id ? (
            <Button htmlType="submit">Create</Button>
          ) : (
            <div>
              <Button htmlType="submit">Update</Button>
              <span style={{ margin: '12px' }} />
              <Button onClick={onCancel}>Cancel</Button>
            </div>
          )}
        </Form.Item>
      </Form>
    ))(this.props)
  }
}

const STATES = ['ONGOING', 'FINISHED', 'CANCELED']

export default (OrderForm as any) as React.ComponentClass<Props>
